package com.ruoyi.project.stop.controller;

import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.constant.ShiroConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.shiro.service.PasswordService;
import com.ruoyi.framework.web.domain.R;
import com.ruoyi.project.stop.domain.StopRecordVO;
import com.ruoyi.project.system.dict.service.IDictTypeService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.stop.domain.StopRecord;
import com.ruoyi.project.stop.service.IStopRecordService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 一键急停记录Controller
 *
 * @author ruoyi
 * @date 2025-02-26
 */
@RestController
@RequestMapping("/stop/record")
public class StopRecordController extends BaseController
{
    private String prefix = "stop/record";

    @Autowired
    private IStopRecordService stopRecordService;

    @Autowired
    private IDictTypeService dictTypeService;

    @Autowired
    private IUserService userService;

    @Autowired
    private PasswordService passwordService;

    @GetMapping()
    public String record()
    {
        return prefix + "/record";
    }

    /**
     * 查询一键急停记录列表
     */

    @ApiOperation("获取最新急停按钮信息")
    @GetMapping("/getLastOne")
    public AjaxResult getInfo()
    {
        StopRecord stopRecord = stopRecordService.selectStopRecordByIdLast();
        if (stopRecord !=null)
        {
            return success(stopRecord);
        }
        else
        {
            return error("数据不存在");
        }
    }

    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(StopRecord stopRecord)
    {
        startPage();
        List<StopRecord> list = stopRecordService.selectStopRecordList(stopRecord);
        return getDataTable(list);
    }

    /**
     * 导出一键急停记录列表
     */
    @Log(title = "一键急停记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(StopRecord stopRecord)
    {
        List<StopRecord> list = stopRecordService.selectStopRecordList(stopRecord);
        ExcelUtil<StopRecord> util = new ExcelUtil<StopRecord>(StopRecord.class);
        return util.exportExcel(list, "一键急停记录数据");
    }

    /**
     * 新增一键急停记录
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存一键急停记录
     */
    @Log(title = "一键急停记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(StopRecordVO stopRecordVO)
    {
        return toAjax(stopRecordService.insertStopRecord(stopRecordVO));
    }


    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        StopRecord stopRecord = stopRecordService.selectStopRecordById(id);
        mmap.put("stopRecord", stopRecord);
        return prefix + "/edit";
    }

    /**
     * 修改保存一键急停记录
     */

    @Log(title = "一键急停记录", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(StopRecord stopRecord)
    {
        return toAjax(stopRecordService.updateStopRecord(stopRecord));
    }

    /**
     * 删除一键急停记录
     */

    @Log(title = "一键急停记录", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(stopRecordService.deleteStopRecordByIds(ids));
    }

    @PostMapping("/autoStop")
    public AjaxResult edit(@RequestParam("isAutoStop") String isAutoStop)
    {

        return toAjax(dictTypeService.updateDictTypeByAutoStop(isAutoStop));
    }

    @GetMapping ("/getAutoStop")
    public Object getAutoStop()
    {
        return success(dictTypeService.getDictTypeByAutoStop());
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password)
    {
        try
        {
            if(StringUtils.isEmpty(username)){
                return error("用户名不可以为空");
            }
            if(StringUtils.isEmpty(password)){
                return error("密码不可以为空");
            }
            // 查询用户信息
            User user = userService.selectUserByLoginName(username);
            if (ObjectUtil.isEmpty(user) || user == null)
            {
                return error("用户不存在");
            }
            // 查询用户密码是否正确
            if (passwordService.matches(user, password))
            {
                return success("登录成功");
            }else {
                return error("用户或密码错误");
            }
        }
        catch (Exception e)
        {
            return error("系统异常，登录失败");
        }
    }

    @PostMapping("/resetPassword")
    @ResponseBody
    public AjaxResult resetPassword(String username, String oldPassword, String newPassword)
    {

        try
        {
            if(StringUtils.isEmpty(username)){
                return error("用户名不可以为空");
            }
            if(StringUtils.isEmpty(oldPassword)){
                return error("旧密码不可以为空");
            }
            if(StringUtils.isEmpty(newPassword)){
                return error("新密码不可以为空");
            }
            // 查询用户信息
            User user = userService.selectUserByLoginName(username);
            if (ObjectUtil.isEmpty(user) || user == null)
            {
                return error("用户不存在");
            }
            if (!passwordService.matches(user, oldPassword))
            {
                return error("修改密码失败，旧密码错误");
            }
            if (passwordService.matches(user, newPassword))
            {
                return error("新密码不能与旧密码相同");
            }
            user.setPassword(newPassword);
            user.setPwdUpdateDate(DateUtils.getNowDate());
            if (userService.resetUserPwd(user) > 0)
            {
                return success("修改密码成功");
            }
            return error("修改密码异常，请联系管理员");
        }
        catch (AuthenticationException e)
        {
            String msg = "系统异常，修改密码失败";
            return error(msg);
        }
    }
}
